package com.stock.core.task;

import com.stock.api.service.stock.HistoryAnalysisService;
import com.stock.comm.util.DateUtil;
import com.stock.core.persistence.reader.stock.HistoryAnalysisReaderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * <p>历史数据分析任务</p>
 *
 * @author 张峰 zfvip_it@163.com
 * @createTime: 2016/9/18 10:00
 */
@Service("historyAnalysisTask")
public class HistoryAnalysisTask extends BaseTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(HistoryAnalysisTask.class);

    @Resource
    private HistoryAnalysisReaderMapper historyAnalysisReaderMapper;

    @Resource
    private HistoryAnalysisService historyAnalysisService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 初始化线程池
     */
    ExecutorService pool = null;

    /**
     * 定时任务处理
     */
    public void run() throws Exception {
        String startDateTime = DateUtil.getCurrentDatetime();
        final String[] stockCodes = new String[]{"601688"};
        int length = stockCodes.length;
        pool = Executors.newFixedThreadPool(length);
        List<Future> rowResult = new CopyOnWriteArrayList<>();
        for (int i = 0; i < length; i++) {
            final String stockCode = stockCodes[i];
            rowResult.add(pool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        redisTemplate.opsForValue().set(stockCode + "HistoryAnalysisMaxTotalAmount", 0);
                        historyAnalysisService.analysisStockHistoryData(stockCode, "20160801");
                    } catch (Exception e) {
                        LOGGER.error("股票【" + stockCode + "】历史数据分析任务失败···", e);
                    }
                }
            }));
        }
        //等待处理结果
        for (Future f : rowResult) {
            f.get();
        }
        //启动一次顺序关闭，执行以前提交的任务，但不接受新任务。如果已经关闭，则调用没有其他作用
        pool.shutdown();
        for (int i = 0; i < length; i++) {
            LOGGER.info("【" + stockCodes[i] + "】买入最大金额：" + redisTemplate.opsForValue().get(stockCodes[i] + "HistoryAnalysisMaxTotalAmount"));
            LOGGER.info("【" + stockCodes[i] + "】当前市值：" + historyAnalysisReaderMapper.getTotalMarketValue(stockCodes[i]));
        }
        String endDateTime = DateUtil.getCurrentDatetime();
        LOGGER.info("历史数据分析任务耗时：" + DateUtil.dateDiff(startDateTime, endDateTime));
    }
}
